package com.ddc.study.feature.main.project.detail;

import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ddc.study.R;
import com.ddc.study.base.TabReselectFragment;
import com.ddc.study.entity.Article;
import com.ddc.study.entity.MainData;
import com.ddc.study.entity.Tree;
import com.ddc.study.feature.html.HtmlActivity;

import java.lang.reflect.Field;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;

/**
 * Created on 2018/8/17.
 *
 * @author lshun
 * @version 1.0
 */
public class DetailFragment extends TabReselectFragment<DetailContract.IView, DetailContract.IPresenter>
        implements DetailContract.IView {
    private Tree mTree;
    private int mPage;//当前已经加载的页码数

//    private List<Tree> mData;

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    private Adapter mAdapter;

    @NonNull
    public static Fragment getInstance(Tree tree) {
        DetailFragment f = new DetailFragment();
        f.mTree = tree;
        return f;
    }

    @Override
    protected DetailContract.IPresenter createPresenter() {
        return new DetailPresenter();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.layout_recycler_with_refresh;
    }

    @Override
    protected void initView() {
        super.initView();

        mSwipeRefreshLayout.setOnRefreshListener(() -> {
            //下拉刷新时重新从第一页开始加载
            mPresenter.loadData(1, mTree.getId());
            mAdapter.setEnableLoadMore(false);
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        if (mAdapter == null) {
            mAdapter = new Adapter();
            mAdapter.bindToRecyclerView(mRecyclerView);
            mAdapter.setOnItemClickListener((adapter, view, position) -> {
                Article article = (Article) adapter.getItem(position);
                if (article != null && getActivity() != null) {
                    HtmlActivity.openUrl(getActivity(), article.getLink());
                }
            });
            mAdapter.setPreLoadNumber(5);
            mAdapter.setOnLoadMoreListener(() -> {
                mPresenter.loadData(mPage + 1, mTree.getId());
                mSwipeRefreshLayout.setEnabled(false);
            }, mRecyclerView);
        } else {
            try {
                Field field = BaseQuickAdapter.class.getDeclaredField("mRecyclerView");
                field.setAccessible(true);
                field.set(mAdapter, null);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
            mAdapter.bindToRecyclerView(mRecyclerView);
            //在销毁重建后需要通知更新视图
            mAdapter.notifyDataSetChanged();
        }

        if (mAdapter.getData().isEmpty()) {
            //无数据时加载数据
            mPresenter.loadData(1, mTree.getId());
            mSwipeRefreshLayout.setRefreshing(true);
            mAdapter.setEnableLoadMore(false);
        }
    }

    @Override
    public void loadDataSuccess(MainData<Article> data) {
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
            mAdapter.setEnableLoadMore(true);
            mPage = 1;
            mAdapter.setNewData(data.getData());
        } else if (mAdapter.isLoading()) {
            mSwipeRefreshLayout.setEnabled(true);
            mPage++;
            mAdapter.addData(data.getData());
            if (data.isDataLoadOver()) {
                mAdapter.loadMoreEnd();
            } else {
                mAdapter.loadMoreComplete();
            }
        }
    }

    @Override
    public void loadDataFailed(String msg) {
        showToast(msg);
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
            mAdapter.setEnableLoadMore(true);
            if (mAdapter.getData().isEmpty()) {
                mAdapter.setEmptyView(R.layout.layout_load_failed, mRecyclerView);
            } else {
                showToast("刷新失败了，请稍候重试~！");
            }
        } else if (mAdapter.isLoading()) {
            mSwipeRefreshLayout.setEnabled(true);
            mAdapter.loadMoreFail();
        }
    }

    @Override
    public void onTabReselect() {
        mRecyclerView.smoothScrollToPosition(0);
    }

    private static final class Adapter extends BaseQuickAdapter<Article, BaseViewHolder> {
        Adapter() {
            super(R.layout.item_project);
        }

        @Override
        protected void convert(BaseViewHolder helper, Article item) {
            helper.setText(R.id.tv_title, item.getTitle())
                    .setText(R.id.tv_desc, item.getDesc())
                    .setText(R.id.tv_time, item.getNiceDate())
                    .setText(R.id.tv_author, item.getAuthor());

            ImageView v = helper.getView(R.id.iv_project_img);
            Glide.with(v.getContext())
                    .load(item.getEnvelopePic())
                    .placeholder(R.mipmap.loading)
                    .error(R.mipmap.failed)
                    .into(v);
        }
    }
}
